{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from os import urandom\n",
    "from hashlib import sha1\n",
    "from random import shuffle, choice"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## algorithm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "puzzle_size = 2 ** 16"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def merkles_puzzle():\n",
    "    secrets = [None] * puzzle_size\n",
    "    puzzles = [None] * puzzle_size\n",
    "\n",
    "    for i in range(puzzle_size):\n",
    "        # generate secret\n",
    "        secrets[i] = urandom(16)\n",
    "\n",
    "        # pair := secret|index\n",
    "        pair = secrets[i] + int.to_bytes(i, 4, 'big')\n",
    "        # plaintext := pair|sha1(pair)\n",
    "        plaintext = pair + sha1(pair).digest()\n",
    "\n",
    "        # cipthertext := ENCRYPT(plaintext, key)\n",
    "        key = urandom(10)\n",
    "        noise = sha1(key).digest()\n",
    "        noise += sha1(noise).digest()\n",
    "        ciphertext = bytes(i ^ j for i, j in zip(plaintext, noise))\n",
    "\n",
    "        # puzzle := ciphertext|key\n",
    "        puzzles[i] = ciphertext + key[2:]\n",
    "\n",
    "    # randomize order\n",
    "    shuffle(puzzles)\n",
    "\n",
    "    # return\n",
    "    return secrets, puzzles"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def solve_puzzle(puzzle):\n",
    "    ciphertext = puzzle[:40]\n",
    "    key = puzzle[40:]\n",
    "\n",
    "    for i in range(puzzle_size):\n",
    "        # guess key\n",
    "        noise = sha1(int.to_bytes(i, 2, 'big') + key).digest()\n",
    "        noise += sha1(noise).digest()\n",
    "\n",
    "        # plaintext := DECRYPT(ciphertext, key)\n",
    "        plaintext = bytes(i ^ j for i, j in zip(ciphertext, noise))\n",
    "\n",
    "        # pair|digest := key|index|sha1(pair)\n",
    "        pair = plaintext[:20]\n",
    "        digest = plaintext[20:]\n",
    "\n",
    "        # on match: time, key, index\n",
    "        if sha1(pair).digest() == digest:\n",
    "            return i, pair[:16], int.from_bytes(pair[16:], 'big')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## (I) alice"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "alice_secrets, public_puzzles = merkles_puzzle()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## (II) bob"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Bob has secret and publishes index\n",
      "key: b'\\xe7.T\\xbd|\\x94\\xa1\\r\\xa3\\xffy\\xab\\x98ZJ\\xb3'\n",
      "index: 52188\n",
      "steps executed: 53788\n"
     ]
    }
   ],
   "source": [
    "bob_time, bob_secret, public_index = solve_puzzle(choice(public_puzzles))\n",
    "\n",
    "print('Bob has secret and publishes index')\n",
    "print('key:', bob_secret)\n",
    "print('index:', public_index)\n",
    "print('steps executed:', bob_time)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## (III) alice"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Alice has secret\n",
      "key: b'\\xe7.T\\xbd|\\x94\\xa1\\r\\xa3\\xffy\\xab\\x98ZJ\\xb3'\n"
     ]
    }
   ],
   "source": [
    "print('Alice has secret')\n",
    "print('key:', alice_secrets[public_index])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## (IV) adversary"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "adversary failed to find secret\n",
      "searched puzzles: 168 steps executed: 5404667\n"
     ]
    }
   ],
   "source": [
    "total_time, total_puzzles = 0, 0\n",
    "\n",
    "for puzzle in public_puzzles:\n",
    "    adv_time, adv_key, adv_index = solve_puzzle(puzzle)\n",
    "    total_time += adv_time\n",
    "    total_puzzles += 1\n",
    "\n",
    "    if adv_index == public_index:\n",
    "        print('very unlikely! adversary found secret:', adv_key)\n",
    "        break\n",
    "\n",
    "    if total_time > bob_time * 100:\n",
    "        print('adversary failed to find secret')\n",
    "        break\n",
    "\n",
    "print('searched puzzles:', total_puzzles, 'steps executed:', total_time)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
